//
//  XDLMRegisteViewController.m
//  xindailianmeng
//
//  Created by 许佳奇 on 17/2/8.
//  Copyright © 2017年 xindailianmeng.cn. All rights reserved.
//**********注册发送验证码页面

#import "XDLMRegisteViewController.h"
#import "InputVertifyView.h"
#import "XDLMGestureViewController.h"
#import "XDLMLoginViewController.h"
#import "AFHTTPSessionManager+POST.h"
#import "XDLMUIFactory.h"
#import "ZHRTRequestFailureShowViewOrDetail.h"
#import "GestureViewController.h"
#define TCOLOR [UIColor colorWithRed:187.0/255.0 green:147.0/255.0 blue:115.0/255.0 alpha:1]
@interface XDLMRegisteViewController ()<UIAlertViewDelegate>
///**
// *  密码输入视图
// */
//@property (nonatomic , strong) XLPasswordInputView  *passwordInputView;
@property (nonatomic, weak) InputVertifyView *inputView;

@property (nonatomic, assign) BOOL isRegister;

@end

@implementation XDLMRegisteViewController
{
    UIView *_backView;
    UILabel *_phoneLab;
    UIButton *_timeBtn;
    NSTimer * _timer;//定时器
    UIView *_topView;
    
    NSInteger _count;
    UIButton *_getYanzhengBtn;
    UIAlertView *_alert;
    NSString *_smsCode;//验证码
    UILabel *_TSLab;//提示lab
    
    UIImageView *_TSImgView;//
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"输入验证码";
    _backView = [[UIView alloc] initWithFrame:kScreenB];
    _backView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:_backView];
    [self addViews];
    
  
}

//数据请求
- (void)loadData
{
    NSString *text = [self.phoneNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSDictionary *param;
    if (self.isLoginCome) {
        
        param = @{@"method":@"login",@"mobile":text,@"smsCode":_smsCode};
    } else {
        param = @{@"method":@"register",@"mobile":text,@"smsCode":_smsCode, @"recommendCode":self.textCode};
        self.isRegister = YES;
    }
    
    [AFHTTPSessionManager POSTWithParams:param success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if ([responseObject[@"code"] isEqualToString:@"100000"]) {
            NSLog(@"%@",responseObject);
            
            NSUserDefaults *df = [NSUserDefaults standardUserDefaults];
            NSString *str = responseObject[@"result"] [@"uid"];
            [df setObject:[NSString stringWithFormat:@"%@",str] forKey:@"uid"];
            NSString *tokenStr =responseObject[@"result"] [@"token"];
            [df setObject:tokenStr forKey:@"token"];
            [df synchronize];
            if (self.isRegister) {
                
                GestureViewController *gestureVc = [[GestureViewController alloc] init];
                gestureVc.type = GestureViewControllerTypeSetting;
                [self.navigationController pushViewController:gestureVc animated:YES];

            } else {
                [self dismissViewControllerAnimated:YES completion:nil];
                if ([df valueForKey:@"isMine"]) {
                    [df removeObjectForKey:@"isMine"];
                    [df synchronize];
                    UITabBarController *tab = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                    tab.selectedIndex = 3;
                    
                }
                
            }
            
        }
        else if([responseObject[@"code"] isEqualToString:@"100005"]){
            _TSImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"gantan"]];
            _TSImgView.frame = CGRectMake(45, 200*kscale, 15, 15);
            _TSImgView.hidden = NO;
            [_backView addSubview:_TSImgView];
            _TSLab = [[UILabel alloc] initWithFrame:CGRectMake(65, 200*kscale, 200, 15)];
            _TSLab.text = responseObject[@"message"];
            _TSLab.font = [UIFont systemFontOfSize:14];
            _TSLab.textColor = [UIColor grayColor];
            _TSLab.hidden = NO;
            [_backView addSubview:_TSLab];
       
        } else {
            
            [ZHRTRequestFailureShowViewOrDetail showViewDetail:responseObject[@"message"] view:self.view];
            
            
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}

//获取验证码
- (void)getMobileCode
{
    NSString *text = [self.phoneNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSDictionary *param = @{@"method":@"getMobileCode",@"mobile":text,@"recommendCode": self.textCode};
    [AFHTTPSessionManager POSTWithParams:param success:^(NSURLSessionDataTask *task, id responseObject)
    {
        
        if ([responseObject[@"code"] isEqualToString:@"100000"])
        {
            NSLog(@"%@",responseObject);
        } else {
             [self againSMSVerify];
            [ZHRTRequestFailureShowViewOrDetail showViewDetail:responseObject[@"message"] view:self.view];
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [self againSMSVerify];
        [ZHRTRequestFailureShowViewOrDetail showViewDetail:@"网络请求失败" view:self.view];
    }];
}
- (void)addViews
{
    //输入框
    InputVertifyView *inputView = [[InputVertifyView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, 300)];
    self.inputView = inputView;
    [_backView addSubview:inputView];

    _topView = [[UIView alloc] initWithFrame:CGRectMake(35, 50*kscale, kScreenW - 70, 40)];
    [_backView addSubview:_topView];
    _phoneLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kScreenW-160, 40)];
    _phoneLab.text = self.phoneNumber;
    _phoneLab.textColor = TCOLOR;
    _phoneLab.font = [UIFont systemFontOfSize:22];
    _phoneLab.textAlignment = NSTextAlignmentCenter;
    _phoneLab.adjustsFontSizeToFitWidth = YES;
    [_topView addSubview:_phoneLab];
    
    _timeBtn = [[UIButton alloc] initWithFrame:CGRectMake(kScreenW-160, 10, 70, 22)];
    _timeBtn.layer.cornerRadius = 12;
    _timeBtn.userInteractionEnabled = NO;
    _timeBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [_timeBtn setTitle:@"60s" forState:UIControlStateNormal];
    [_timeBtn setBackgroundColor:[UIColor grayColor]];
    [_timeBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [_timeBtn addTarget:self action:@selector(timeBtnBeClick) forControlEvents:UIControlEventTouchUpInside];
    [_topView addSubview:_timeBtn];
    _count = 60;
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerDidClick) userInfo:nil repeats:YES];
    [_timer setFireDate:[NSDate distantPast]];

    
    
    UILabel *goalLab = [[UILabel alloc] initWithFrame:CGRectMake(0, kScreenH - 150*kscale, kScreenW, 60)];
    goalLab.textColor = TCOLOR;
    goalLab.text = @"定一个小目标，先赚他一个亿";
    goalLab.font = [UIFont systemFontOfSize:FONTSIZE18];
    goalLab.textAlignment = NSTextAlignmentCenter;
    [_backView addSubview:goalLab];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNoti:) name:@"VerCodePost" object:nil];
    
}

#pragma mark -- 监听

- (void)receiveNoti:(NSNotification *)noti {
    
    _smsCode = noti.object;
    
//    if (self.isLoginCome == YES) {
        [self loadData];
//    }else{
//        [self loadRegisterData];
//    }
    
}
// timer
- (void)timerDidClick {
    _count -= 1;
    [_timeBtn setTitle:[NSString stringWithFormat:@"%lds", (long)_count] forState:UIControlStateNormal];
    if (_count == 0) {
        
        [self againSMSVerify];
    }
}
// 验证请求失败后重新发送设置
- (void)againSMSVerify {
    _count = 60;
    [_timer setFireDate:[NSDate distantFuture]];
    [_timeBtn setTitle:@"重新发送" forState:UIControlStateNormal];
    _timeBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
    _timeBtn.userInteractionEnabled = YES;
    
    _phoneLab.frame = CGRectMake(0, 0, kScreenW-200
                                 , 40);
    _timeBtn.frame = CGRectMake(kScreenW-195, 10, 50, 22);
    
    
    _getYanzhengBtn = [[UIButton alloc] initWithFrame:CGRectMake(kScreenW-200+70, 16, 54, 12)];
    [_getYanzhengBtn setBackgroundImage:[UIImage imageNamed:@"meishoudao"] forState:UIControlStateNormal];
    [_topView addSubview:_getYanzhengBtn];
}
#pragma mark -- 点击方法
- (void)timeBtnBeClick
{
    [_timer setFireDate:[NSDate distantPast]];
    [self getMobileCode];
}
- (void)leftItemClick
{
  
            _alert = [[UIAlertView alloc] initWithTitle:@"" message:@"验证码在赶来的路上..." delegate:self cancelButtonTitle:@"算了" otherButtonTitles:@"等等", nil];
            [_alert show];

}
#pragma mark -- alertviewdelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
  
        [self.navigationController popViewControllerAnimated:YES];
    }
}
//点击空白区域，隐藏键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    //结束编辑
    [self.view endEditing:YES];
}
#pragma mark --辅助方法
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self getMobileCode];
    [self createLeftItem];
}
- (void)createLeftItem
{
    UIBarButtonItem *leftItem = [XDLMUIFactory createBBIWithImageStr:@"back" target:self action:@selector(leftItemClick)];
    self.navigationItem.leftBarButtonItem = leftItem;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:@"VerCodePost"];
}

@end
